import { createVNode, render } from 'vue';
import MyMessage from './Message.vue';

const parentNode = document.createElement('div');

let timer = null;
const Message = options => {
  renderMsg(options);
};

Message.primary = (content, delay) => {
  renderMsg({ type: 'primary', content, delay });
};
Message.success = (content, delay) => {
  renderMsg({ type: 'success', content, delay });
};
Message.warning = (content, delay) => {
  renderMsg({ type: 'warning', content, delay });
};
Message.error = (content, delay) => {
  renderMsg({ type: 'error', content, delay });
};

const renderMsg = ({ type, content, delay = 3500 }) => {
  const vNode = createVNode(MyMessage, { type, content, delay });

  render(null, parentNode);
  document.body.appendChild(parentNode);
  render(vNode, parentNode);

  clearTimeout(timer);
  timer = setTimeout(() => {
    document.body.removeChild(parentNode);
    render(null, parentNode);
    clearTimeout(timer);
  }, delay);
};

export default Message;
